import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Navigator, Image, ScrollView, Block} from '@tarojs/components'
import {connect} from 'react-redux'
import Skeleton from 'taro-skeleton'
import {
  CityLocation as CityLocationType,
  SubCategory,
  Good
} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {
  IDENTITY_IS_SELLER,
  LIST_CATEGORY,
  RESOURCE_URL,
  SCAN_BIND_SELLER, TARO_ENV,
  UPDATE_USER_SHARE_DATE,
  SCENIC_INDEX_RECMV2
} from '../../constants/api'
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import CityLocation from '../../components/city-location/city-location'
import MainMenu from '../../components/main-menu/main-menu'
import BigGoodsBox from '../../components/big-goods-box/big-goods-box'
import SwiperRecommend from '../../components/swiper-recommend/swiper-recommend'
import {getHeadTop, vcmonitor, clearSearch} from '../../utils/tools'
import {user} from '../../utils/user.service'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Share from '../../components/share/share'
import HeaderBar from "../components/header-bar/header-bar";
import {location as locationServer} from "../../utils/location.service";
import AdvertisementMember from "../../components/advertisement/member";
import {getMemberAdvertisement} from "../../utils/getCommonData";
import './index.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  systemInfo: any
  headTopAll: any
  memberAdvertisement: any
  linkUri: string
  searchText: string
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  goods: Good[]
  isAll: boolean
  showLeftIcon: boolean
  isActive: boolean
  categoryIdOld: number
  depth: number
  subCategory: SubCategory[]
  subCategoryConvert: any
  pageData: any
  scrollTop: any
  bottomNavId: number
  headTop: { statusBar: number; top: number }
  showLoading: boolean
  isUser: boolean
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {

  state: PageState = {
    systemInfo: {},
    headTopAll: 0,
    scrollTop: 0,
    isActive: true,
    categoryIdOld: 0,
    depth: 0,
    linkUri: '',
    searchText: '',
    memberAdvertisement: '',
    loadMoreStatus: 'loading',
    goods: [],
    subCategory: [],
    subCategoryConvert: [],
    pageData: {
      headBg: "https://resource.ivcheng.com/resources/system/img/scenic.jpg",
      pageTitle: "景点详情",
      menus: [],
      adImg: {
        img: "",
        url: ""
      },
      recommondGoods: [],
    },
    bottomNavId: 0,
    headTop: {
      statusBar: 0,
      top: 0,
    },
    showLeftIcon: true,
    isAll: true,
    showLoading: true,
    isUser: true
  }

  async UNSAFE_componentWillMount() {
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({systemInfo: res})
      }
    })
    const params = Taro.getCurrentInstance().router.params
    const categoryId = params.categoryId || 0
    const pageData: any = await http.get(SCENIC_INDEX_RECMV2, {style: 0})
    if (!pageData) {
      return false
    }
    const headTop: any = getHeadTop()
    this.setState({
      showLeftIcon: process.env.P_ENV !== 'kontai',
      headTop,
      bottomNavId: categoryId,
      pageData,
      headTopAll: headTop.statusBar + headTop.top,
      showLoading: false
    })
  }

  async componentDidShow() {
    await vcmonitor(this)
    const locationData = Taro.getStorageSync('locationData') || ''
    if (!locationData) {
      locationServer.getLocation().then(async (res: any) => {
        if (res) {
          Taro.setStorageSync('locationData', res);
        }
        await this.handlerDidShow()
      })
    } else {
      await this.handlerDidShow()
    }
  }

  page = 0
  shareParams = ''

  async handlerDidShow() {
    clearSearch()
    this.page = 1
    const {categoryId = 0, bindSellerId = '', tempSellerId = ''} = Taro.getCurrentInstance().router.params
    this.setState({categoryIdOld: categoryId, memberAdvertisement: await getMemberAdvertisement({ position: 'jingdian' })})
    const goods = await this.getGoods(this.page, categoryId)
    const categoryData = (await http.HGet(LIST_CATEGORY, {type: 1, c: categoryId})) || {}
    if (categoryData.data.some((item) => item.id === categoryId)) {
      this.setState({isActive: false})
    }
    if (categoryData.data.length > 0) {
      this.setState({depth: categoryData.data[0].depth})
    }
    this.setState({
      goods,
      subCategory: categoryData.data,
      subCategoryConvert: categoryData.data.map(item => ({
        name: item.name, id: item.id, url: item.link, urlType: item.link_type,
        depth: item.depth
      })),
      isAll: categoryData.is_all
    })
    if (this.state.pageData.pageTitle) {
      await Taro.setNavigationBarTitle({
        title: this.state.pageData.pageTitle
      })
    }
    this.shareParams = await user.getSellerParams()
    let link = '/common/scenic/index?' + this.shareParams
    if (process.env.TARO_ENV === 'h5') {
      link = window.location.origin + link
      const shareData = {
        title: platform.info.platformName,
        desc: '景点门票',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    } else {
      link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({linkUri: link, isUser})
    const bindSellerIds = bindSellerId
    const tempSellerIds = tempSellerId
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      path: this.state.linkUri
    }
  }

  onShareTimeline() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      query: this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
    }
  }

  async getGoods(page = 1, categoryId) {
    const location: any = Taro.getStorageSync('locationData');
    const params = {
      areaId: this.props.location.region_id,
      p: page,
      s: 10,
      k: this.state.searchText,
      c: categoryId
    }
    if (location) {
      params.lng = location.longitude || ''
      params.lat = location.latitude || ''
    }
    // 商品列表
    const goodsData = await fetchNewGoodsList.getGoodsList({
      module_type: "4",
      data_type: "2",
      page,
      length: 10,
      region_category: categoryId === 0 ? "" : categoryId
    });
    // const goodsData: any = await newHttp.catchGet<CategoryListPageGood[]>(CATEGORY_SCENIC_PAGE, params)
    if (goodsData && Array.isArray(goodsData)) {
      if (goodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.bottomNavId)
      this.setState({goods})
    })
  }

  searchClear() {
    this.page = 1
    this.setState({searchText: '', loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.bottomNavId)
      this.setState({goods})
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData: any = await this.getGoods(this.page, this.state.bottomNavId)
      this.setState({goods: [...old, ...newData]})
    }
  }

  inputChange(value) {
    this.setState({searchText: value})
  }

  async subCategoryClick(id, depth) {
    this.page = 1
    let data
    if (depth === 0) { // 全部
      if (this.state.depth === 2) { // 三级
        // 没有下级
        const goods = await this.getGoods(this.page, this.state.categoryIdOld)
        this.setState({goods, isActive: true, bottomNavId: this.state.categoryIdOld})
      } else if (this.state.depth === 1) { // 有下级
        this.setState({isActive: true, bottomNavId: 0, goods: []})
        data = await http.HGet(LIST_CATEGORY, {c: id, type: 1, category: 0, depth})
        if (data.data.length > 0) {
          const goods: any = await this.getGoods(this.page, this.state.categoryIdOld)
          if (goods.length > 0) {
            this.setState({
              goods, isAll: data.is_all, subCategory: data.data, subCategoryConvert: data.data.map(item => ({
                name: item.name, id: item.id, url: item.link, urlType: item.link_type,
                depth: item.depth
              }))
            })
          }
        }
      }
    } else {
      if (depth === 2) { // 没有下架
        const goods = await this.getGoods(this.page, id)
        this.setState({isActive: false, goods, bottomNavId: id})
      } else { // 有下级
        data = await http.HGet(LIST_CATEGORY, {c: id, type: 1, depth})
        if (data && data.data.length > 0) {
          this.setState({goods: [], bottomNavId: id, isActive: false})
          const goods: any = await this.getGoods(this.page, id)
          if (goods.length > 0) {
            if (data.data[0].id !== this.state.subCategory[0].id) {
              this.setState({
                bottomNavId: 0,
                isActive: true,
                isAll: data.is_all,
                subCategory: data.data,
                subCategoryConvert: data.data.map(item => ({
                  name: item.name, id: item.id, url: item.link, urlType: item.link_type,
                  depth: item.depth
                }))
              })
            }
            this.setState({goods})
          }
        }
      }
    }
  }

  onPageScroll(page) {
    this.setState({scrollTop: page.scrollTop})
  }

  render() {
    const {
      linkUri,
      systemInfo,
      scrollTop,
      goods,
      isUser,
      subCategoryConvert,
      pageData,
      bottomNavId,
      headTop,
      showLoading,
      isAll,
      headTopAll,
      showLeftIcon,
      memberAdvertisement,
      isActive
    } = this.state
    const offSetTop = scrollTop > 100 ? 100 : scrollTop
    const xAxis = 50 - offSetTop / 3.8
    const top = headTopAll + 40 - offSetTop / 2.5
    const maxWidth = systemInfo.screenWidth - 20
    const width = maxWidth - (offSetTop + offSetTop * 0.2)
    const smallBar = headTop.statusBar > 20 ? headTopAll + 88 : headTopAll + 98
    return (
      <View className='scenic-root' id='root'>
        <GzhAuth />
        <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='150px'>
          <Block>
            {(TARO_ENV !== 'h5' && TARO_ENV !== 'tt') &&
            <View className='header-bar' style={`width: ${offSetTop > 80 ? 'inherit' : '100%'};`}><HeaderBar
              showLeftIcon={showLeftIcon} opacity={offSetTop > 40 ? 0 : 1} title={pageData.pageTitle}
            /></View>}
            <View className='head'>
              <View className='search-bar'
                style={`opacity: ${scrollTop >= 100 ? 1 : 0};left: ${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? '50' : xAxis}%;transform: translateX(-${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? '50' : xAxis}%);width: ${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? maxWidth : width}px;max-width: ${maxWidth}px;top: ${top}px;`}
              >
                {(scrollTop >= 100) && <CityLocation />}
              </View>
            </View>
            <View className='head-back-img'><Image className='img' src={pageData.headBg} mode='widthFix' /></View>
            <View className='head-bg'
              style={`height:${headTopAll + 45}px;background: rgba(242,242,242,${Math.min(offSetTop / 100, 1)});`}
            />
          </Block>
        </Skeleton>
        <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='300px'>
          <Block>
            <View className='zoom' style='margin-top: 10px;'>
              {pageData.menus && pageData.menus.length > 0 && <View className='categorys'>
                <MainMenu data={pageData.menus} index={+pageData.rowNum} />
              </View>}
              {pageData && pageData.recommondGoods && pageData.recommondGoods.length > 0 &&
              <View className='recommend'>
                <SwiperRecommend title='人气必玩' data={pageData.recommondGoods} showLabel
                  showMore={false}
                />
              </View>}
              {pageData && pageData.adImg && pageData.adImg.img &&
              <Navigator className='ad-module' url={pageData.adImg.url}>
                <Image className='img' src={pageData.adImg.img} mode='aspectFill' />
              </Navigator>}
              {(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') && !!platform.info && !!platform.info.applicationOpenVip && memberAdvertisement &&
              <View style='margin: 0 10px;'>
                <AdvertisementMember url={memberAdvertisement} />
              </View>}
              <View className='bottom-nav'
                style={`top: ${smallBar}px;`}
              >
                <View className='main'>精挑细选</View>
                <ScrollView scrollX enable-flex className='subNav-scenic'>
                  <View className='nav-box'>
                    {isAll && <View key={0} onClick={this.subCategoryClick.bind(this, 0, 0)}
                      className={`nav-item ${isActive ? 'active' : ''}`}
                    >全部</View>}
                    {subCategoryConvert.length > 0 && subCategoryConvert.map(item =>
                      <View key={item.id} onClick={this.subCategoryClick.bind(this, item.id, item.depth)}
                        className={`nav-item ${bottomNavId === item.id ? 'active' : ''}`}
                      >{item.name}</View>
                    )}
                  </View>
                </ScrollView>
              </View>
              <View className='bottom-goods'>
                <BigGoodsBox isUser={isUser} data={goods} />
                {goods && goods.length == 0 &&
                <View className='listNull'>
                  <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
                  <View className='text'>什么都没有,去看看别的吧~</View>
                </View>
                }
              </View>
            </View>
          </Block>
        </Skeleton>
        <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='150px'>
          <Block>
            {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} linkUri={linkUri} />}
          </Block>
        </Skeleton>
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
